#include <iostream>
#include <fstream>
#include <cstring>
#include <iomanip>
#include "base.h"

namespace lmf {

using std::cerr;
using std::endl;


bool is_exist(const char* cN)
{
	return std::ifstream(cN,std::ios::in)==NULL?0:1;
}

Base::Base()
{
	strcpy(cName,"Empty");
	return;
}

Base::Base(const char* cN,int ds) : dat_size(ds)
{
	if(is_exist(cN))
		open(cN,dat_size);
	else
		create(cN,dat_size);
	return;
}

bool Base::open(const char* cN,int ds)
{
	if(fsFile.is_open())
	{
		cerr << "The base is already opened" << endl;
		return 1;
	}
	fsFile.open(cN,std::ios::in | std::ios::out | std::ios::binary | std::ios::ate);
	if(!fsFile.is_open())
	{
		cerr << "No such a file" << endl;
		return 1;
	}
	dat_size=ds;
	strcpy(cName,cN);
	return 0;
}

bool Base::create(const char* cN,int ds)
{
	if(fsFile.is_open())
	{
		cerr << "The base is already opened" << endl;
		return 1;
	}
	if(is_exist(cN))
	{
		cerr << "The base exists, rewrite [y/n]" << endl;
		char cDes;
		std::cin >> cDes;
		if(cDes!='y' && cDes!='Y')
		{
			cerr << "Interrupted" << endl;
			return 1;
		}
	}
	fsFile.open(cN,std::ios::in | std::ios::out | std::ios::binary | std::ios::trunc);
	dat_size=ds;
	strcpy(cName,cN);
	return 0;
}

bool Base::close()
{
	if(!fsFile.is_open())
	{
		cerr << "The base is not opened" << endl;
		return 1;
	}
	fsFile.close();
	strcpy(cName,"Empty");
	return 0;
}

int Base::gsize()
{
    unsigned int lines;
    fsFile.seekp(0L,std::ios::end);
    lines=fsFile.tellp()/dat_size;
    return lines;
}

Base::~Base()
{
	if(fsFile.is_open())
		(*this).close();
	return;
}

}
